using DevExpress.XtraGrid.Views.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

public class MaterialGroupForm : Form
{
    public MaterialGroupForm()
    {
        InitializeComponent();
        gridView1.CustomUnboundColumnData += gridView1_CustomUnboundColumnData;
        comboBoxEditType.Properties.Items.Clear();
        comboBoxEditType.Properties.Items.AddRange(new string[] { "原材料", "半成品", "成品", "其他" });
        comboBoxEditType.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
        btnModify.Click += btnModify_Click;
        btnQuery.Click += btnQuery_Click;
        btnDelete.Click += btnDelete_Click;
        btnRefresh.Click += (s, e) => RefreshAndBind();
        this.Load += (s, e) => RefreshAndBind();
    }

    private void RefreshAndBind(IEnumerable<object> data = null)
    {
        if (data == null)
        {
            data = LoadAllMaterialGroups();
        }
        gridControl1.DataSource = data.ToList();
        gridView1.PopulateColumns();
        RemoveUnwantedColumns();
        EnsureSerialNumberColumn();
        FillTypeComboBox(data);
    }

    private void btnQuery_Click(object sender, EventArgs e)
    {
        string code = textEditCode.Text.Trim();
        string name = textEditName.Text.Trim();
        string type = comboBoxEditType.Text.Trim();
        var data = LoadAllMaterialGroups().Where(item =>
        {
            var t = item.GetType();
            string codeVal = t.GetProperty("MaterialGroupCode")?.GetValue(item)?.ToString() ?? "";
            string nameVal = t.GetProperty("MaterialGroupName")?.GetValue(item)?.ToString() ?? "";
            string typeVal = t.GetProperty("MaterialType")?.GetValue(item)?.ToString() ?? "";
            return (string.IsNullOrEmpty(code) || codeVal.Contains(code)) &&
                   (string.IsNullOrEmpty(name) || nameVal.Contains(name)) &&
                   (string.IsNullOrEmpty(type) || typeVal == type);
        });
        RefreshAndBind(data);
    }

    private void btnModify_Click(object sender, EventArgs e)
    {
        var selectedRows = gridView1.GetSelectedRows();
        if (selectedRows.Length != 1)
        {
            MessageBox.Show("请只选择一条要修改的数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
        var group = gridView1.GetRow(selectedRows[0]) as MaterialForm.MaterialModel;
        if (group == null)
        {
            MessageBox.Show("未获取到物料群组信息！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }
        var updateForm = new UpdateMaterialForm(group);
        if (updateForm.ShowDialog() == DialogResult.OK)
        {
            RefreshAndBind();
        }
    }

    private void btnDelete_Click(object sender, EventArgs e)
    {
        var selectedRows = gridView1.GetSelectedRows();
        if (selectedRows.Length == 0)
        {
            MessageBox.Show("请先选择要删除的数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
        foreach (var rowHandle in selectedRows)
        {
            var group = gridView1.GetRow(rowHandle) as MaterialForm.MaterialModel;
            if (group != null)
            {
                // TODO: 调用你的删除API
                // DeleteMaterialGroup(group.Id);
            }
        }
        RefreshAndBind();
    }

    private void RemoveUnwantedColumns()
    {
        string[] unwanted = { "IsDeleted", "DeletedAt" };
        foreach (var colName in unwanted)
        {
            if (gridView1.Columns[colName] != null)
                gridView1.Columns.Remove(gridView1.Columns[colName]);
        }
    }

    private void EnsureSerialNumberColumn()
    {
        if (gridView1.Columns["序号"] == null)
        {
            var col = gridView1.Columns.AddField("序号");
            col.Caption = "序号";
            col.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
            col.Visible = true;
            col.VisibleIndex = 0;
        }
        else
        {
            gridView1.Columns["序号"].Visible = true;
            gridView1.Columns["序号"].VisibleIndex = 0;
        }
    }

    private void gridView1_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e)
    {
        if (e.Column.FieldName == "序号" && e.IsGetData)
        {
            e.Value = e.ListSourceRowIndex + 1;
        }
    }

    private void FillTypeComboBox(IEnumerable<object> data)
    {
        var types = data.Select(item =>
        {
            var t = item.GetType();
            return t.GetProperty("MaterialType")?.GetValue(item)?.ToString() ?? "";
        }).Where(s => !string.IsNullOrEmpty(s)).Distinct().ToList();
        comboBoxEditType.Properties.Items.Clear();
        comboBoxEditType.Properties.Items.AddRange(types);
    }

    // TODO: 替换为你的实际数据加载方法
    private IEnumerable<object> LoadAllMaterialGroups()
    {
        // return ...;
        return new List<object>();
    }
} 